C, C++ (http://www.moskalyuk.com/jobs/index.htm)

Q: How do you link a C++ program to C functions?

A: By using the extern "C" linkage specification around the C function declarations.

Q: Explain the scope resolution operator.

A: It permits a program to reference an identifier in the global scope that has been hidden by another identifier with the same name in the local scope.

Q: What are the differences between a C++ struct and C++ class?

A: The default member and base-class access specifiers are different.

Q: How many ways are there to initialize an int with a constant?

A: Two.

There are two formats for initializers in C++ as shown in the example that follows. The first format uses the traditional C notation. The second format uses constructor notation.

int foo = 123;

int bar (123);

Q: How does throwing and catching exceptions differ from using setjmp and longjmp?

A: The throw operation calls the destructors for automatic objects instantiated since entry to the try block.

Q: What is your reaction to this line of code?

delete this;

A: It's not a good practice.

Q: What is a default constructor?

A: A constructor that has no arguments.

Q: What is a conversion constructor?

A: A constructor that accepts one argument of a different type.

Q: What is the difference between a copy constructor and an overloaded assignment operator?

A: A copy constructor constructs a new object by using the content of the argument object. An overloaded assignment operator assigns the contents of an existing object to another existing object of the same class.

Q: When should you use multiple inheritance?

A: There are three acceptable answers: "Never," "Rarely," and "When the problem domain cannot be accurately modeled any other way."

Q: What is a virtual destructor?

A: The simple answer is that a virtual destructor is one that is declared with the virtual attribute.

Q: Explain the ISA and HASA class relationships. How would you implement each in a class design?

A: A specialized class "is" a specialization of another class and, therefore, has the ISA relationship with the other class. An Employee ISA Person. This relationship is best implemented with inheritance. Employee is derived from Person. A class may have an instance of another class. For example, an employee "has" a salary, therefore the Employee class has the HASA relationship with the Salary class. This relationship is best implemented by embedding an object of the Salary class in the Employee class.

Q: When is a template a better solution than a base class?

A: When you are designing a generic class to contain or otherwise manage objects of other types, when the format and behavior of those other types are unimportant to their containment or management, and particularly when those other types are unknown (thus, the genericity) to the designer of the container or manager class.

Q: What is a mutable member?

A: One that can be modified by the class even when the object of the class or the member function doing the modification is const.

Q: What is an explicit constructor?

A: A conversion constructor declared with the explicit keyword. The compiler does not use an explicit constructor to implement an implied conversion of types. It's purpose is reserved explicitly for construction.

Q: What is the Standard Template Library?

A: A library of container templates approved by the ANSI committee for inclusion in the standard C++ specification.

A programmer who then launches into a discussion of the generic programming model, iterators, allocators, algorithms, and such, has a higher than average understanding of the new technology that STL brings to C++ programming.

Q: Describe run-time type identification.

A: The ability to determine at run time the type of an object by using the typeid operator or the dynamic_cast operator.

Q: What problem does the namespace feature solve?

A: Multiple providers of libraries might use common global identifiers causing a name collision when an application tries to link with two or more such libraries. The namespace feature surrounds a library's external declarations with a unique namespace that eliminates the potential for those collisions.

This solution assumes that two library vendors don't use the same namespace identifier, of course.

Q: Are there any new intrinsic (built-in) data types?

A: Yes. The ANSI committee added the bool intrinsic type and its true and false value keywords.

 

General Programming

Puzzles, Riddles and Others
0. Classic: If a bear walks one mile south, turns left and walks one mile to the east and then turns left again and walks one mile north and arrives at its original position, what is the color of the bear.

ANS. The color of the bear is trivial. The possible solutions to it are interesting. In addition to the trivial north pole and circle near north pole solutions, there is an additional circle near south pole solution. Think it out.

* 1. Given a rectangular (cuboidal for the puritans) cake with a rectangular piece removed (any size or orientation), how would you cut the remainder of the cake into two equal halves with one straight cut of a knife?

ANS. Join the centers of the original and the removed rectangle. It works for cuboids too!

2. There are 3 baskets. one of them have apples, one has oranges only and the other has mixture of apples and oranges. The labels on their baskets always lie. (i.e. if the label says oranges, you are sure that it doesn't have oranges only,it could be a mixture) The task is to pick one basket and pick only one fruit from it and then correctly label all the three baskets.

HINT. There are only two combinations of distributions in which ALL the baskets have wrong labels. By picking a fruit from the one labeled MIXTURE, it is possible to tell what the other two baskets have.

3. You have 8 balls. One of them is defective and weighs less than others. You have a balance to measure balls against each other. In 2 weighings how do you find the defective one?

4. Why is a manhole cover round?

HINT. The diagonal of a square hole is larger than the side of a cover!

Alternate answers: 1. Round covers can be transported by one person, because they can be rolled on their edge. 2. A round cover doesn't need to be rotated to fit over a hole.

5. How many cars are there in the USA?

6. You've got someone working for you for seven days and a gold bar to pay them. The gold bar is segmented into seven connected pieces. You must give them a piece of gold at the end of every day. If you are only allowed to make two breaks in the gold bar, how do you pay your worker?

7. One train leaves Los Angeles at 15mph heading for New York. Another train leaves from New York at 20mph heading for Los Angeles on the same track. If a bird, flying at 25mph, leaves from Los Angeles at the same time as the train and flies back and forth between the two trains until they collide, how far will the bird have traveled?

HINT. Think relative speed of the trains.

8. You have two jars, 50 red marbles and 50 blue marbles. A jar will be picked at random, and then a marble will be picked from the jar. Placing all of the marbles in the jars, how can you maximize the chances of a red marble being picked? What are the exact odds of getting a red marble using your scheme?

9. Imagine you are standing in front of a mirror, facing it. Raise your left hand. Raise your right hand. Look at your reflection. When you raise your left hand your reflection raises what appears to be his right hand. But when you tilt your head up, your reflection does too, and does not appear to tilt his/her head down. Why is it that the mirror appears to reverse left and right, but not up and down?

10. You have 5 jars of pills. Each pill weighs 10 gram, except for contaminated pills contained in one jar, where each pill weighs 9 gm. Given a scale, how could you tell which jar had the contaminated pills in just one measurement?

ANS. 1. Mark the jars with numbers 1, 2, 3, 4, and 5.
2. Take 1 pill from jar 1, take 2 pills from jar 2, take 3 pills from jar 3, take 4 pills from jar 4 and take 5 pills from jar 5.
3. Put all of them on the scale at once and take the measurement.
4. Now, subtract the measurment from 150 ( 1*10 + 2*10 + 3*10 + 4*10 + 5*10)
5. The result will give you the jar number which has contaminated pill.

11. If you had an infinite supply of water and a 5 quart and 3 quart pail, how would you measure exactly 4 quarts?

12. You have a bucket of jelly beans. Some are red, some are blue, and some green. With your eyes closed, pick out 2 of a like color. How many do you have to grab to be sure you have 2 of the same?

13. Which way should the key turn in a car door to unlock it?

14. If you could remove any of the 50 states, which state would it be and why?

15. There are four dogs/ants/people at four corners of a square of unit distance. At the same instant all of them start running with unit speed towards the person on their clockwise direction and will always run towards that target. How long does it take for them to meet and where?

HINT. They will meet in the centre and the distance covered by them is independent of the path they actually take (a spiral).

16. (fram Tara Hovel) A helicopter drops two trains, each on a parachute, onto a straight infinite railway line. There is an undefined distance between the two trains. Each faces the same direction, and upon landing, the parachute attached to each train falls to the ground next to the train and detaches. Each train has a microchip that controls its motion. The chips are identical. There is no way for the trains to know where they are. You need to write the code in the chip to make the trains bump into each other. Each line of code takes a single clock cycle to execute.
You can use the following commands (and only these);
MF - moves the train forward
MB - moves the train backward
IF (P) - conditional that's satisfied if the train is next to a parachute. There is no "then" to this IF statement.
GOTO


ANS.
A: MF
IF (P)
GOTO B
GOTO A
-----
B: MF
GOTO B
Explanation: The first line simply gets them off the parachutes. You need to get the trains off their parachutes so the back train can find the front train's parachute, creating a special condition that will allow it to break out of the code they both have to follow initially. They both loop through A: until the back train finds the front train's parachute, at which point it goes to B: and gets stuck in that loop. The front train still hasn't found a parachute, so it keeps in the A loop. Because each line of code takes a "clock cycle" to execute, it takes longer to execute the A loop than the B loop, therefore the back train (running in the B loop) will catch up to the front train.

Personality
It is best to read some website or a book for questions like these. 1. Tell me the courses you liked and why did you like them.
2. Give an instance in your life in which u were faced with a problem and you tackled it successfully.

3. What is your ideal working environment. ( They usually to hear that u can work in group also.)

4. Why do u think u are smart.

5. Questions on the projects listed on the Resume.

6. Do you want to know any thing about the company.( Try to ask some relevant and interesting question).

7. How long do u want to stay in USA and why?

8. What are your geographical preference?

9. What are your expectations from the job.


Algorithms and Programming
1. Given a rectangular (cuboidal for the puritans) cake with a rectangular piece removed (any size or orientation), how would you cut the remainder of the cake into two equal halves with one straight cut of a knife ?

2. You're given an array containing both positive and negative integers and required to find the subarray with the largest sum (O(N) a la KBL). Write a routine in C for the above.

3. Given an array of size N in which every number is between 1 and N, determine if there are any duplicates in it. You are allowed to destroy the array if you like. [ I ended up giving about 4 or 5 different solutions for this, each supposedly better than the others ].

4. Write a routine to draw a circle (x ** 2 + y ** 2 = r ** 2) without making use of any floating point computations at all. [ This one had me stuck for quite some time and I first gave a solution that did have floating point computations ].

5. Given only putchar (no sprintf, itoa, etc.) write a routine putlong that prints out an unsigned long in decimal. [ I gave the obvious solution of taking % 10 and / 10, which gives us the decimal value in reverse order. This requires an array since we need to print it out in the correct order. The interviewer wasn't too pleased and asked me to give a solution which didn't need the array ].

6. Give a one-line C expression to test whether a number is a power of 2. [No loops allowed - it's a simple test.]

7. Given an array of characters which form a sentence of words, give an efficient algorithm to reverse the order of the words (not characters) in it.

8. How many points are there on the globe where by walking one mile south, one mile east and one mile north you reach the place where you started.

9. Give a very good method to count the number of ones in a 32 bit number. (caution: looping through testing each bit is not a solution).

10. What are the different ways to say, the value of x can be either a 0 or a 1. Apparently the if then else solution has a jump when written out in assembly. if (x == 0) y=0 else y =x There is a logical, arithmetic and a datastructure soln to the above problem.

11. Reverse a linked list.

12. Insert in a sorted list

13. In a X's and 0's game (i.e. TIC TAC TOE) if you write a program for this give a gast way to generate the moves by the computer. I mean this should be the fasteset way possible. The answer is that you need to store all possible configurations of the board and the move that is associated with that. Then it boils down to just accessing the right element and getting the corresponding move for it. Do some analysis and do some more optimization in storage since otherwise it becomes infeasible to get the required storage in a DOS machine.

14. I was given two lines of assembly code which found the absolute value of a number stored in two's complement form. I had to recognize what the code was doing. Pretty simple if you know some assembly and some fundaes on number representation.

15. Give a fast way to multiply a number by 7.

16. How would go about finding out where to find a book in a library. (You don't know how exactly the books are organized beforehand).

17. Linked list manipulation.

18. Tradeoff between time spent in testing a product and getting into the market first.

19. What to test for given that there isn't enough time to test everything you want to.

20. First some definitions for this problem: a) An ASCII character is one byte long and the most significant bit in the byte is always '0'. b) A Kanji character is two bytes long. The only characteristic of a Kanji character is that in its first byte the most significant bit is '1'.

Now you are given an array of a characters (both ASCII and Kanji) and, an index into the array. The index points to the start of some character. Now you need to write a function to do a backspace (i.e. delete the character before the given index).

21. Delete an element from a doubly linked list.

22. Write a function to find the depth of a binary tree.

23. Given two strings S1 and S2. Delete from S2 all those characters which occur in S1 also and finally create a clean S2 with the relevant characters deleted.

24. Assuming that locks are the only reason due to which deadlocks can occur in a system. What would be a foolproof method of avoiding deadlocks in the system.

25. Reverse a linked list.

Ans: Possible answers -

iterative loop
curr->next = prev;
prev = curr;
curr = next;
next = curr->next
endloop

recursive reverse(ptr)
if (ptr->next == NULL)
return ptr;
temp = reverse(ptr->next);
temp->next = ptr;
return ptr;
end


26. Write a small lexical analyzer - interviewer gave tokens. expressions like "a*b" etc.

27. Besides communication cost, what is the other source of inefficiency in RPC? (answer : context switches, excessive buffer copying). How can you optimise the communication? (ans : communicate through shared memory on same machine, bypassing the kernel _ A Univ. of Wash. thesis)

28. Write a routine that prints out a 2-D array in spiral order!

29. How is the readers-writers problem solved? - using semaphores/ada .. etc.

30. Ways of optimizing symbol table storage in compilers.

31. A walk-through through the symbol table functions, lookup() implementation etc - The interv. was on the Microsoft C team.

32. A version of the "There are three persons X Y Z, one of which always lies".. etc..

33. There are 3 ants at 3 corners of a triangle, they randomly start moving towards another corner.. what is the probability that they don't collide.

34. Write an efficient algo and C code to shuffle a pack of cards.. this one was a feedback process until we came up with one with no extra storage.

35. The if (x == 0) y = 0 etc..

36. Some more bitwise optimization at assembly level

37. Some general questions on Lex, Yacc etc.

38. Given an array t[100] which contains numbers between 1..99. Return the duplicated value. Try both O(n) and O(n-square).

39. Given an array of characters. How would you reverse it. ? How would you reverse it without using indexing in the array.

40. GIven a sequence of characters. How will you convert the lower case characters to upper case characters. ( Try using bit vector - sol given in the C lib -typec.h)

41. Fundas of RPC.

42. Given a linked list which is sorted. How will u insert in sorted way.

43. Given a linked list How will you reverse it.

44. Give a good data structure for having n queues ( n not fixed) in a finite memory segment. You can have some data-structure separate for each queue. Try to use at least 90% of the memory space.

45. Do a breadth first traversal of a tree.

46. Write code for reversing a linked list.

47. Write, efficient code for extracting unique elements from a sorted list of array. e.g. (1, 1, 3, 3, 3, 5, 5, 5, 9, 9, 9, 9) -> (1, 3, 5, 9).

48. Given an array of integers, find the contiguous subarray with the largest sum.

ANS. Can be done in O(n) time and O(1) extra space. Scan array from 1 to n. Remember the best subarray seen so far and the best subarray ending in i.

49. Given an array of length N containing integers between 1 and N, determine if it contains any duplicates.

ANS. [Is there an O(n) time solution that uses only O(1) extra space and does not destroy the original array?]

50. Sort an array of size n containing integers between 1 and K, given a temporary scratch integer array of size K.

ANS. Compute cumulative counts of integers in the auxiliary array. Now scan the original array, rotating cycles! [Can someone word this more nicely?]

* 51. An array of size k contains integers between 1 and n. You are given an additional scratch array of size n. Compress the original array by removing duplicates in it. What if k << n?

ANS. Can be done in O(k) time i.e. without initializing the auxiliary array!

52. An array of integers. The sum of the array is known not to overflow an integer. Compute the sum. What if we know that integers are in 2's complement form?

ANS. If numbers are in 2's complement, an ordinary looking loop like for(i=total=0;i 53. An array of characters. Reverse the order of words in it.

ANS. Write a routine to reverse a character array. Now call it for the given array and for each word in it.

* 54. An array of integers of size n. Generate a random permutation of the array, given a function rand_n() that returns an integer between 1 and n, both inclusive, with equal probability. What is the expected time of your algorithm?

ANS. "Expected time" should ring a bell. To compute a random permutation, use the standard algo of scanning array from n downto 1, swapping i-th element with a uniformly random element <= i-th. To compute a unformly random integer between 1 and k (k < n), call rand_n() repeatedly until it returns a value in the desired range.

55. An array of pointers to (very long) strings. Find pointers to the (lexicographically) smallest and largest strings.

ANS. Scan array in pairs. Remember largest-so-far and smallest-so-far. Compare the larger of the two strings in the current pair with largest-so-far to update it. And the smaller of the current pair with the smallest-so-far to update it. For a total of <= 3n/2 strcmp() calls. That's also the lower bound.

56. Write a program to remove duplicates from a sorted array.

ANS. int remove_duplicates(int * p, int size)
{
int current, insert = 1;
for (current=1; current < size; current++)
if (p[current] != p[insert-1])
{
p[insert] = p[current];
current++;
insert++;
} else
current++;

return insert;

}


57. C++ ( what is virtual function ? what happens if an error occurs in constructor or destructor. Discussion on error handling, templates, unique features of C++. What is different in C++, ( compare with unix).

58. Given a list of numbers ( fixed list) Now given any other list, how can you efficiently find out if there is any element in the second list that is an element of the first list (fixed list).

59. GIven 3 lines of assembly code : find it is doing. IT was to find absolute value.

60. If you are on a boat and you throw out a suitcase, Will the level of water increase.

61. Print an integer using only putchar. Try doing it without using extra storage.

62. Write C code for (a) deleting an element from a linked list (b) traversing a linked list

63. What are various problems unique to distributed databases

64. Declare a void pointer ANS. void *ptr;

65. Make the pointer aligned to a 4 byte boundary in a efficient manner ANS. Assign the pointer to a long number and the number with 11...1100 add 4 to the number

66. What is a far pointer (in DOS)

67. What is a balanced tree

68. Given a linked list with the following property node2 is left child of node1, if node2 < node1 else, it is the right child.

O P
|
|
O A
|
|
O B
|
|
O C

How do you convert the above linked list to the form without disturbing the property. Write C code for that.


O P
|
|
O B
/ \
/ \
/ \
O ? O ?

determine where do A and C go

69. Describe the file system layout in the UNIX OS

ANS. describe boot block, super block, inodes and data layout

70. In UNIX, are the files allocated contiguous blocks of data

ANS. no, they might be fragmented

How is the fragmented data kept track of

ANS. Describe the direct blocks and indirect blocks in UNIX file system

71. Write an efficient C code for 'tr' program. 'tr' has two command line arguments. They both are strings of same length. tr reads an input file, replaces each character in the first string with the corresponding character in the second string. eg. 'tr abc xyz' replaces all 'a's by 'x's, 'b's by 'y's and so on. ANS.
a) have an array of length 26.
put 'x' in array element corr to 'a'
put 'y' in array element corr to 'b'
put 'z' in array element corr to 'c'
put 'd' in array element corr to 'd'
put 'e' in array element corr to 'e'
and so on.

the code
while (!eof)
{
c = getc();
putc(array[c - 'a']);
}

72. what is disk interleaving

73. why is disk interleaving adopted

74. given a new disk, how do you determine which interleaving is the best a) give 1000 read operations with each kind of interleaving determine the best interleaving from the statistics

75. draw the graph with performace on one axis and 'n' on another, where 'n' in the 'n' in n-way disk interleaving. (a tricky question, should be answered carefully)

76. I was a c++ code and was asked to find out the bug in that. The bug was that he declared an object locally in a function and tried to return the pointer to that object. Since the object is local to the function, it no more exists after returning from the function. The pointer, therefore, is invalid outside.

77. A real life problem - A square picture is cut into 16 sqaures and they are shuffled. Write a program to rearrange the 16 squares to get the original big square.

78.
int *a;
char *c;
*(a) = 20;
*c = *a;
printf("%c",*c);

what is the output?

79. Write a program to find whether a given m/c is big-endian or little-endian!

80. What is a volatile variable?

81. What is the scope of a static function in C ?

82. What is the difference between "malloc" and "calloc"?

83. struct n { int data; struct n* next}node;
node *c,*t;
c->data = 10;
t->next = null;
*c = *t;
what is the effect of the last statement?


Networks and Security
1. How do you use RSA for both authentication and secrecy?

2. What is ARP and how does it work?

3. What's the difference between a switch and a router?

4. Name some routing protocols? (RIP,OSPF etc..)

5. How do you do authentication with message digest(MD5)? (Usually MD is used for finding tampering of data)

6. How do you implement a packet filter that distinguishes following cases and selects first case and rejects second case.

i) A host inside the corporate n/w makes a ftp request to outside host and the outside host sends reply.

ii) A host outside the network sends a ftp request to host inside. for the packet filter in both cases the source and destination feilds will look the same.

7. How does traceroute works? Now how does traceroute makes sure that the packet follows the same path that a previous (with ttl - 1) probe packet went in?

8. Explain Kerberos Protocol ?

9. What are digital signatures and smart cards?

10. Difference between discretionary access control and mandatory access control?


Java
1. How do you find the size of a java object (not the primitive type) ?

ANS. type cast it to string and find its s.length()

2. Why is multiple inheritance not provided in Java?

3. Thread t = new Thread(); t.start(); t = null; now what will happen to the created thread?

4. How is garbage collection done in java?

5. How do you write a "ping" routine in java?

6. What are the security restrictions on applets?

Linked lists
* 0. Under what circumstances can one delete an element from a singly linked list in constant time?

* 1. Given a singly linked list, determine whether it contains a loop or not.

2. Given a singly linked list, print out its contents in reverse order. Can you do it without using any extra space?

3. Given a binary tree with nodes, print out the values in pre-order/in-order/post-order without using any extra space.

4. Reverse a singly linked list recursively. The function prototype is node * reverse (node *) ;

5. Given a singly linked list, find the middle of the list.

Hints and Answers

0. If the list is circular and there are no references to the nodes in the list from anywhere else! Just copy the contents of the next node and delete the next node. If the list is not circular, we can delete any but the last node using this idea. In that case, mark the last node as dummy!

1. (a) Start reversing the list. If you reach the head, gotcha! there is a loop!

But this changes the list. So, reverse the list again.

(b) Maintain two pointers, initially pointing to the head. Advance one of them one node at a time. And the other one, two nodes at a time. If the latter overtakes the former at any time, there is a loop!

p1 = p2 = head;

do {
p1 = p1->next;
p2 = p2->next->next;
} while (p1 != p2);

2. Start reversing the list. Do this again, printing the contents.

3. [Yet to think about]

4. node * reverse (node * n)
{
node * m ;

if (! (n && n -> next))
return n ;

m = reverse (n -> next) ;
n -> next -> next = n ;
n -> next = NULL ;
return m ;
}

5. Use the single and double pointer jumping. Maintain two pointers, initially pointing to the head. Advance one of them one node at a time. And the other one, two nodes at a time. When the double reaches the end, the single is in the middle. This is not asymptotically faster but seems to take less steps than going through the list twice.


Bit-manipulation
* 1. Reverse the bits of an unsigned integer.

* 2. Compute the number of ones in an unsigned integer.

3. Compute the discrete log of an unsigned integer.

* 4. How do we test most simply if an unsigned integer is a power of two?

5. Set the highest significant bit of an unsigned integer to zero.

6. Let f(k) = y where k is the y-th number in the increasing sequence of non-negative integers with the same number of ones in its binary representation as y, e.g. f(0) = 1, f(1) = 1, f(2) = 2, f(3) = 1, f(4) = 3, f(5) = 2, f(6) = 3 and so on. Given k >= 0, compute f(k).

Hints and Answers

1. #define reverse(x) \
(x=x>>16|(0x0000ffff&x)<<16, \
x=(0xff00ff00&x)>>8|(0x00ff00ff&x)<<8, \
x=(0xf0f0f0f0&x)>>4|(0x0f0f0f0f&x)<<4, \
x=(0xcccccccc&x)>>2|(0x33333333&x)<<2, \
x=(0xaaaaaaaa&x)>>1|(0x55555555&x)<<1)

2. #define count_ones(x) \
(x=(0xaaaaaaaa&x)>>1+(0x55555555&x), \
x=(0xcccccccc&x)>>2+(0x33333333&x), \
x=(0xf0f0f0f0&x)>>4+(0x0f0f0f0f&x), \
x=(0xff00ff00&x)>>8+(0x00ff00ff&x), \
x=x>>16+(0x0000ffff&x))

3. #define discrete_log(h) \
(h=(h>>1)|(h>>2), \
h|=(h>>2), \
h|=(h>>4), \
h|=(h>>8), \
h|=(h>>16), \
h=(0xaaaaaaaa&h)>>1+(0x55555555&h), \
h=(0xcccccccc&h)>>2+(0x33333333&h), \
h=(0xf0f0f0f0&h)>>4+(0x0f0f0f0f&h), \
h=(0xff00ff00&h)>>8+(0x00ff00ff&h), \
h=(h>>16)+(0x0000ffff&h))
If I understand it right, log2(2) =1, log2(3)=1, log2(4)=2..... But this macro does not work out log2(0) which does not exist! How do you think it should be handled?


4. #define power_of_two(x) \ ((x)&&(~(x&(x-1))))

5. (from Denis Zabavchik) Set the highest significant bit of an unsigned integer to zero
#define zero_most_significant(h) \
(h&=(h>>1)|(h>>2), \
h|=(h>>2), \
h|=(h>>4), \
h|=(h>>8), \
h|=(h>>16))


Graphics
1. Write a function to check if two rectangles defined as below overlap or not. struct rect { int top, bot, left, right; } r1, r2;

2. Write a SetPixel(x, y) function, given a pointer to the bitmap. Each pixel is represented by 1 bit. There are 640 pixels per row. In each byte, while the bits are numbered right to left, pixels are numbered left to right. Avoid multiplications and divisions to improve performance.


Databases
* 1. You, a designer want to measure disk traffic i.e. get a histogram showing the relative frequency of I/O/second for each disk block. The buffer pool has b buffers and uses LRU replacement policy. The disk block size and buffer pool block sizes are the same. You are given a routine int lru_block_in_position (int i) which returns the block_id of the block in the i-th position in the list of blocks managed by LRU. Assume position 0 is the hottest. You can repeatedly call this routine. How would you get the histogram you desire?

Hints and Answers

1. Simply do histogram [lru_block_in_position (b-1)] ++ at frequent intervals... The sampling frequency should be close to the disk I/O rate. It can be adjusted by remembering the last block seen in position b. If same, decrease frequency; if different, increase, with exponential decay etc. And of course, take care of overflows in the histogram.


Semaphores
1. Implement a multiple-reader-single-writer lock given a compare-and-swap instruction. Readers cannot overtake waiting writers.


Others
1. A character set has 1 and 2 byte characters. One byte characters have 0 as the first bit. You just keep accumulating the characters in a buffer. Suppose at some point the user types a backspace, how can you remove the character efficiently. (Note: You cant store the last character typed because the user can type in arbitrarily many backspaces)

2. What is the simples way to check if the sum of two unsigned integers has resulted in an overflow.

3. How do you represent an n-ary tree? Write a program to print the nodes of such a tree in breadth first order.

4. Write the 'tr' program of UNIX. Invoked as

tr -str1 -str2. It reads stdin and prints it out to stdout, replacing every occurance of str1[i] with str2[i].

e.g. tr -abc -xyz
to be and not to be <- input
to ye xnd not to ye <- output

Development for Microsoft platforms

1. The three types of DAO Dynaset,Snapshot,Table
2. Why do we use Option Explicit
3. Difference between Dim Object as object AND dim obj as myform
4. How do we make a poperty read only? Private Property Get(Read Only )
5. How do you declare an object in VBscript? Dim object
6. What is the equivalent of VBScript's On Error In Jscript ??
7. How many data types are supported in Vbscript
8. MFC
9. Java
10. Active Server Pages
11. What are session variables??
12. In what languages in ASP written.
13. How do you create Virtual Root in IIS
14. How do you remotely administer MS IIS??
15. What is the key advantage of Windows NT Challenge/Response security?
16. What problems do the vendors of ODBC Technology face with ASP/ADO ?
18. How do you administer Connection Pooling in IIS 3.0
19. How do you administer Connection Pooling in IIS 4.0
20. What are the three Ado objects?? --Connection,command, recordset
21. Two Methods of retrieving SQL
22. How do you assign Construct the where clause without concatenating Field,
value pairs??
23. What cursor type do you use to retrieve multiple recordsets?
24. What action do you have to perform before retrieving data from the next
result set of a stored procedure ??
25. What are The three tags of a form tag in HTML form
26. What are The two tags for framesets
27. How do you create Drop Down Combos in HTML ? select Tag
28. In DHTML what is the difference between FontSize and Font Size ??
A: FontSize is a property, Font Size is a style
29. What is the tag Code Base and why do we use it?
30. How can you have different number of cells for each row of a table?

31. The three file types in NT ? NTFS,Macintosh(HPFS), FAT
32. Describe a two tier Windows NT Domain?
33. Define and explain COM
34. What is IUnknown and what are its three parts??

35. Define Query Interface,Adref,Release
36. Do COM keep track of all the object references(Accounting)??
37. What is Marshalling
38. When is Marshalling not necessary??

Databases

1. What is a Cartesian product? What causes it?

Expected answer:
A Cartesian product is the result of an unrestricted join of two or more tables. The result set of a three table Cartesian product will have x * y * z number of rows where x, y, z correspond to the number of rows in each table involved in the join. It is causes by specifying a table in the FROM clause without joining it to another table.

2. What is an advantage to using a stored procedure as opposed to passing an SQL query from an application.

Expected answer:
A stored procedure is pre-loaded in memory for faster execution. It allows the DBMS control of permissions for security purposes. It also eliminates the need to recompile components when minor changes occur to the database.

3. What is the difference of a LEFT JOIN and an INNER JOIN statement?

Expected answer:
A LEFT JOIN will take ALL values from the first declared table and matching values from the second declared table based on the column the join has been declared on. An INNER JOIN will take only matching values from both tables

4. When a query is sent to the database and an index is not being used, what type of execution is taking place?

Expected answer:
A table scan.

5. What are the pros and cons of using triggers?

Expected answer:
A trigger is one or more statements of SQL that are being executed in event of data modification in a table to which the trigger belongs.

Triggers enhance the security, efficiency, and standardization of databases.
Triggers can be beneficial when used:
-- to check or modify values before they are actually updated or inserted in the database. This is useful if you need to transform data from the way the user sees it to some internal database format.
-- to run other non-database operations coded in user-defined functions
-- to update data in other tables. This is useful for maintaining relationships between data or in keeping audit trail information.
-- to check against other data in the table or in other tables. This is useful to ensure data integrity when referential integrity constraints aren't appropriate, or when table check constraints limit checking to the current table only.

6. What are the pros and cons of using stored procedures. When would you use them?

7. What are the pros and cons of using cursors? When would you use them?

UML Questions used by a software company

Q. What does "object-oriented" mean to you?

Q. Can you name the four phases of the Unified Process?
A. Inception
Elaboration
Construction
Transition

Q. What can you tell us about the different phases of the Unified Process?

Q. Talk about some OO/UML artifacts you have used. What did they mean to you? How did you apply them to yout project?

Q. What is a "use case"?
A. A complete end-to-end business process that satisfies the needs of a user.

Q. What are different categories of use cases?
A. Detail Level: - High level / Expanded
Task Level: - Super / Sub (Abstract; Equal Alternatives; Complete v. Partial)
Importance: - Primary / Secondary (use Secondary for exceptional processes)
Abstraction: - Essential / Real
Q. What is the difference between a real and essential use case?
A. essential - describes the "essence" of the problem; technology independent
real - good for GUI designing; shows problem as related to technology decisions
Q. What is polymorphism?
A. Different objects reacting to the same message differently.

Q. In a System Sequence Diagram, what is a System Event?
A. It is from the expanded use case. It is an actor action the system directly responds to.

Q. Give an example of a situation which a State Diagram could effectively model.
A. Think of a cake and its different stages through the baking process: dough, baked, burned.

Q. For what are Operations Contracts written?
A. System Events.

Q. In an Operations Contract's postconditions, four types of activities are specified. What are they?
A. They are:

instances created
associations formed
associations broken
attributes changed
Q. What does an Operations Contract do?
A. Provides a snapshot of the System's state before and after a System Event. It is not interested in the Event's specific behavior.

Q. What does a Collaboration Diagram (or Sequence Event, depending on the process) model?
A. A System Event's behavior.

Q. How does one model a class in a Collaboration Diagram? An instance?
A. A box will represent both; however, a class is written as MyClass whereas an instance is written as myInstance:MyClass.

Q. What are the three parts of a class in a Class Diagram?
A. Name, Attributes, Methods.

Q. In Analysis, we are interested in documenting concepts within the relevant problem domain. What is a concept?
A. A person, place, thing, or idea that relates to the problem domain. They are candidates for objects.

Q. Does a concept HAVE to become a class in Design?
A. No.

Q. In a Class Diagram, what does a line with an arrow from one class to another denote?
A. Attribute visibility.

Q. What are the four types of visibility between objects?
A. Local, parameter, attribute, global.

Q. Have you ever used any Design Patterns?

Q. When do you use inheritance as opposed to aggregation?
A. An aggregation is a "has a" relationship, and it is represented in the UML by a clear diamond. An example of an aggregate relation is Table of Contents and Chapter. A Table of Contents "has a" Chapter.

Q. When would I prefer to use composition rather than aggregation?
A. Composition is a stronger form of aggregation. The object which is "contained" in another object is expected to live and die with the object which "contains" it. Composition is represented in the UML by a darkened diamond. An example of a composite relation is a Book and Chapter. A Book "has a" Chapter, and the Chapter cannot exist without the Book.

Q. Is the UML a process, method, or notation?
A. It is a notation. A process is Objectory, Booch, OMT, or the Unified Process. A process and a notation together make an OO method.

Q. What are two uses for inheritance?
A. specialization - "IS A KIND OF" relationship
abstraction - pull a common concept out to a higher level to make it more generic
Q. When would you use an abstract base class
A. When you need to enforce a particular interface, but are not able or do not need to define behavior at the base class level.

Q. All containers are pretty well templatized now. Can you think of any current "example" (e.g., an algorithm) which is implemented via inheritance but might be more efficiently implemented using templates?

Q. Can you tell us some good principles to use in OOA&D?
A. NOTE: This is not a complete list, by any means, but we have listed the GRASP Patterns here for examples (these help assign responsibilities between objects):

Low coupling
High cohesion
Controller
Creator
Don't Talk to Strangers
Pure Fabrication
Indirection
Polymorphism
Expert
 

Q. What are some practicle benefits we can gain from a well-designed OO system?

VB-ASP

1. How do you register a component?

Expected answer:
Compiling the component, running REGSVR32 MyDLL.dll

2. Name and explain the different compatibility types when creating a COM component.

Expected answer:
No Compatibility ? New GUID created, references from other components will not work
Project Compatibility ? Default for a new component <Not as critical to mention this one>
Binary Compatibility ? GUID does not change, references from other components will work

3. Why is it important to use source control software for source code?

Expected answer:
Modification history.
Code ownership: Multiple people can not modify the same code at the same time.

4. What two methods are called from the ObjectContext object to inform MTS that the transaction was successful or unsuccessful?

Expected answer:
SetComplete and SetAbort.

5. What is the tool used to configure the port range and protocols for DCOM communications?

Expected answer:
DCOMCONFIG.EXE

6. What does Option Explicit refer to?

Expected answer:
All variables must be declared before use. Their type is not required.

7. What are the different ways to Declare and Instantiate an object in Visual Basic 6?

Expected answer:

Dim obj as OBJ.CLASS with either
Set obj = New OBJ.CLASS or
Set obj = CreateObject(?OBJ.CLASS?) or
Set obj = GetObject( ,? OBJ.CLASS?)
or
Dim obj as New OBJ.CLASS

8. Name the four different cursor types in ADO and describe them briefly.

Expected Answer:
The cursor types are listed from least to most resource intensive.
Forward Only ? Fastest, can only move forward in recordset
Static ? Can move to any record in the recordset. Data is static and never changes.
KeySet ? Changes are detectable, records that are deleted by other users are unavailable, and records created by other users are not detected
Dynamic ? All changes are visible.

9. Name the four different locking type in ADO and describe them briefly.

Expected Answer:
LockPessimistic ? Locks the row once after any edits occur.
LockOptimistic ? Locks the row only when Update is called.
LockBatchOptimistic ? Allows Batch Updates.
LockReadOnly ? Read only. Can not alter the data.

10. Describe Database Connection pooling (relative to MTS )

Expected Answer:
This allows MTS to reuse database connections. Database connections are put to ?sleep? as opposed to being created and destroyed and are activated upon request.

11. What are the ADO objects? Explain them. Provide a scenario using three of them to return data from a database.

Expected Answer:
Connection ? Connects to a data source; contains the Errors collection
Command ? Executes commands to the data source. Is the only object that can accept parameters for a stored procedure.
Recordset ? The set of data returned from the database.

Scenario: There are many possibilities. The most likely is as follows:
Dim conn As ADODB.Connection
Dim rs As ADODB.Recordset
Dim Cmd As ADODB.Command

conn.ConnectionString = ?CONNECTION STRING?
conn.Open

Set Cmd.ActiveConnection = conn
Cmd.CommandText = ?SQL STATEMENT?

Set rs = Cmd.Execute
Set rs.ActiveConnection = Nothing
conn.Close

12. Under the ADO Command Object, what collection is responsible for input to stored procedures?

Expected answer:
The Parameters collection.

13. What are some benefits of using MTS?

Expected answer:
Database Pooling, Transactional operations, Deployment, Security, Remote Execution.

14. What is the benefit of wrapping database calls into MTS transactions?

Expected answer:
If database calls are made within the context of a transaction, aborting the transaction will undo and changes that occur within that transaction. This removes the possibility of stranded, or partial data.

15. Describe and In Process vs. Out of Process component. Which is faster?

Expected answer:
An in-process component is implemented as a DLL, and runs in the same process space as its client app, enabling the most efficient communication between client and component.Each client app that uses the component starts a new instance of it.

An out of process component is implemented as an EXE, and unlike a dll, runs in its own process space. As a result, exe's are slower then dll's because communications between client and component must be marshalled across process boundaries. A single instance of an out of process component can service many clients.

15. What are the main components of the ADO object model? How are they used?

Expected answer:
Connection: Used to make a connection between your app and an external data source, ie, sql server.

Command: Used to build queries, including user-specific parameters, to access records from a data source (which are returned in a Recordset)

Recordset:Used to access records returned from an SQL query. With a recordset, you can navigate returned records. You can also add, modify or delete records.

CPP,Networking

Q1: Could you tell something about the Unix System Kernel? (from ITCO )

A1: The kernel is the heart of the UNIX openrating system, it's reponsible for controlling the computer's resouces and scheduling user jobs so that each one gets its fair share of resources.

 

Q2: What are each of the standard files and what are they normally associated with? (from ITCO )

A2: They are the standard input file, the standard output file and the standard error file. The first is usually associated with the keyboard, the second and third are usually associated with the terminal screen.

 

Q3: Detemine the code below, tell me exectly how many times is the operation sum++ performed ? (from ITCO )

for ( i = 0; i < 100; i++ )
for ( j = 100; j > 100 - i; j--)
sum++;
A3: (99 * 100)/2 = 4950
The sum++ is performed 4950 times.

 

Q4: Give 4 examples which belongs application layer in TCP/IP architecture? (from CISCO )

A4: FTP, TELNET, HTTP and TFTP

 

Q5: What's the meaning of ARP in TCP/IP? (from CISCO )

A5: The "ARP" stands for Address Resolution Protocol. The ARP standard defines two basic message types: a request and a response. a request message contains an IP address and requests the corresponding hardware address; a replay contains both the IP address, sent in the request, and the hardware address.

UNIX

What is LILO?

LILO stands for Linex boot loader. It will load the MBR, master boot record, into the memory, which tell the system which partition and harddrive to boot.

 

What is the main advantage of creating links to a file instead of copies of the file?
A: The main advantage is not really that it saves disk space (though it does that too) but, rather, that a change of permissions on the file is applied to all the link access points. The link will show permissions of lrwxrwxrwx but that is for the link itself and not the access to the file to which the link points. Thus if you want to change the permissions for a command, such as su, you only have to do it on the original. With copies you have to find all of the copies and change permission on each of the copies.

 

Write a command to find all of the files which have been accessed within the last 30 days.
A: find / -type f -atime -30 > December.files &
This command will find all the files under root, which is '/', with file type is file. '-atime -30' will give all the files accessed less than 30 days ago. And the output will put into a file call December.files.

 

What is the most graceful way to get to run level single user mode?

A: The most graceful way is to use the command init s.
If you want to shut everything down before going to single user mode then do init 0 first and from the ok prompt do a boot -s.

 

What does the following command line produce? Explain each aspect of this line.
$ (date ; ps -ef | awk {print $1}' | sort | uniq | wc -l ) >> Activity.log

A: First let's dissect the line: The date gives the date and time as the first command of the line, this is followed by the a list of all running processes in long form with UIDs listed first, this is the ps -ef. These are fed into the awk which filters out all but the UIDs; these UIDs are piped into sort for no discernible reason and then onto uniq (now we see the reason for the sort - uniq only works on sorted data - if the list is A, B, A, then A, B, A will be the output of uniq, but if it's A, A, B then A, B is the output) which produces only one copy of each UID. These UIDs are fed into wc -l which counts the lines - in this case the number of distinct UIDs running processes on the system. Finally the results of these two commands, the date and the wc -l, are appended to the file "Activity.log". Now to answer the question as to what this command line produces. This writes the date and time into the file Activity.log together with the number of distinct users who have processes running on the system at that time. If the file already exists, then these items are appended to the file, otherwise the file is created.

WEB-Development, PERL

Q1: How can we store the information returned from querying the database? and if it is too big, how does it affect the performance?

Answ: In Java the return information will be stored in the ResultSet object. Yes, if the ResultSet is getting big, it will slow down the process and the performance as well. We can prevent this situation by give the program a simple but specific query statement.

Q2: What is index table and why we use it?

Answ: Index table are based on a sorted ordering of the values. Index table provides fast access time when searching.

Q3: In Java why we use exceptions?

Answ: Java uses exceptions as a way of signaling serious problems when you execute a program. One major benefit of having an error signaled by an exception is that it separates the code that deals with errors from the code that is executed when things are moving along smoothly. Another positive aspect of exceptions is that they provide a way of enforcing a response to particular errors.

Q4: Write a code in Perl that makes a connection to Database.

Answ: #!\usr\bin\perl
#makeconnection.plx

use warnings;
use strick;
use DBI;
my $dbh = DBI->connect('dbi:mysql:test','root','foo')||
die "Error opening database: $DBI::errstr\n";
print"Successful connect to database\n";
$dbh->disconnect || die "Failed to disconnect\n?;
print "Goodbye\n";

Q5: Write a code in Perl that select all data from table Foo.?

Answ: #!usr\bin\perl
#connect.plx

use warnings;
use strick;
use DBI;

my ($dbh, $sth, $name, $id);

$dbh= DBI->connect('dbi:mysql:test','root','foo')||
die "Error opening database: $DBI::errstr\n";

$sth= $dbh->prepare("SELECT * from Foo;") ||
die "Prepare failed: $DBI::errstr\n";
$sth->execute() ||
die "Couldn't execute query: $DBI::errstr\n";

while(( $id, $name) = $sth->fetchrow_array) {
print "$name has ID $id\n";
}

$sth->finish();
$dbh->disconnect || die "Failed to disconnect\n";

WEB-Development,DataStructures

Question: What is an HTML tag?
Answer: An HTML tag is a syntactical construct in the HTML language that abbreviates specific instruction to be executed when the HTML script is loaded into a Web brower. It is like a method in Java, a function in C++, a procedure in Pascal, or a routine in FORTRAN.
Question: What is polymorphism?
Answer: In object-oriented programming, the term "polymorphism" refers to the ability of objects to take the form objects of difference classes.
Question: What is the difference between a component and a container?
Answer:
A component is an object, like a button or a sroll bar, that has a visual representation in a sreen window.
A container is a window-like component that can contain other components.
Every component has a unique container that directly contains it.
Question: What is the difference between a constructor and a method?
Answer:
A constructor is a member function of a class that is used to create objects of that class. It has the same name as the class itself, has no return type, and is invoked using the new operator.
A method is an ordinary member function of a class. It has its own name, a return type (which may be void), and is invoked using the dot operator.
Question: What are the advantages and disadvantages of using an AVL tree?

Answer:
The advantage of an AVL tree is that it is always balanced, guaranteeing the O(lgn) speed of the Binary Search algorithm.
The disadvantages the complex rotations used by the insertion and removal algorithms needed to maintain the tree's balance.

Web-Development-Networking

Q: How would you make the following SQL statement run faster? SELECT * FROM TABLEA WHERE COL1='A' AND COL2='B';
A: Make sure that COL1 and COL2 have indexes.
Find out which condition will return less values and use that as the first conditonal.


Q: What is Data Mining
A: Data Minig is the process of sifting through extremeley large amounts of Data to find trends or relevent information.


Q: Name the Seven layers in the OSI Model.
A: Appication, Presentation, Session, Transport, Network, Data Link, Phyiscal


Q: What is one way to view a unix network share on a Windows computer, within explorer
A: NFS, The Unix computer can be running a NFS Server Daemon.


Q: How would you find all the processes running on your computer.
A: Unix, is ps -ef or ps -aux depending on version.


Q: What is DHCP
A: DHCP is a way to dynamically assign IP address to computers. Dyanmic Host Configuration Protocol


Q: What is HTTP Tunneling
A: HTTP Tunneling is a security method that encryptes packets traveling throught the internet. Only the intended reciepent should be able to decrypt the packets. Can be used to Create Virtual Private Networks. (VPN)


Q: Scenario: You have 9 identical looking balls, however one ball is heavier than the others. You have two chances to use a balance. How do you find out which ball is the heaviest?
A: Split into groups of three, randomly choose two groups and use balance on them. If one group is heavier, then discard the other 6 balls. If the two groups are the same weight. The heavier ball must be in the group that was not on the scale. Now randomly choose two balls and test on balance. If they are the same weight, the heaviest ball is on one that was not tested. Else the heaviest ball is already known from the balance.

JAVA-C++

Q1: What are the advantages of OOPL?

Ans: Object oriented programming languages directly represent the real life objects. The features of OOPL as inhreitance, polymorphism, encapsulation makes it powerful.

Q2: What do mean by polymorphisum, inheritance, encapsulation?

Ans: Polymorhisum: is a feature of OOPl that at run time depending upon the type of object the appropriate method is called.
Inheritance: is a feature of OOPL that represents the "is a" relationship between different objects(classes). Say in real life a manager is a employee. So in OOPL manger class is inherited from the employee class.
Encapsulation: is a feature of OOPL that is used to hide the information.

Q3: What do you mean by static methods?

Ans: By using the static method there is no need creating an object of that class to use that method. We can directly call that method on that class. For example, say class A has static function f(), then we can call f() function as A.f(). There is no need of creating an object of class A.

Q4: What do you mean by virtual methods?

Ans: virtual methods are used to use the polymorhism feature in C++. Say class A is inherited from class B. If we declare say fuction f() as virtual in class B and override the same function in class A then at runtime appropriate method of the class will be called depending upon the type of the object.

Q5: Given two tables Student(SID, Name, Course) and Level(SID, level) write the SQL statement to get the name and SID of the student who are taking course = 3 and at freshman level.

Ans: SELECT Student.name, Student.SID
FROM Student, Level
WHERE Student.SID = Level.SID
AND Level.Level = "freshman"
AND Student.Course = 3;

Q6: What are the disadvantages of using threads?

Ans: DeadLock.

 

Q1: Write the Java code to declare any constant (say gravitational constant) and to get its value

Ans: Class ABC
{
static final float GRAVITATIONAL_CONSTANT = 9.8;
public void getConstant()
{
system.out.println("Gravitational_Constant: " + GRAVITATIONAL_CONSTANT);
}
}
Q2: What do you mean by multiple inheritance in C++ ?


Ans: Multiple inheritance is a feature in C++ by which one class can be of different types. Say class teachingAssistant is inherited from two classes say teacher and Student.

Q3: Can you write Java code for declaration of multiple inheritance in Java ?

Ans: Class C extends A implements B
{
}

Networking

What is UTP?

UTP -- Unshielded twisted pair 10BASE-T is the preferred Ethernet medium of the 90s. It is based on a star topology and provides a number of advantages over coaxial media:

It uses inexpensive, readily available copper phone wire. UTP wire is much easier to install and debug than coax. UTP uses RG-45 connectors, which are cheap and reliable.

What is a router? What is a gateway?

Routers are machines that direct a packet through the maze of networks that stand between its source and destination. Normally a router is used for internal networks while a gateway acts a door for the packet to reach the ‘outside’ of the internal network

What is Semaphore? What is deadlock?

Semaphore is a synchronization tool to solve critical-section problem, can be used to control access to the critical section for a process or thread. The main disadvantage (same of mutual-exclusion) is require busy waiting. It will create problems in a multiprogramming system, where a single CPU is shared among many processes.

Busy waiting wastes CPU cycles.

Deadlock is a situation when two or more processes are waiting indefinitely for an event that can be caused by only one of the waiting processes. The implementation of a semaphore with a waiting queue may result in this situation.

What is Virtual Memory?

Virtual memory is a technique that allows the execution of processes that may not be completely in memory. A separation of user logical memory from physical memory allows an extremely large virtual memory to be provided for programmers when only a smaller physical memory is available. It is commonly implemented by demand paging. A demand paging system is similar to a paging system with swapping. Processes reside on secondary memory (which is usually a disk). When we want to execute a process, we swap it into memory.

Explain the layered aspect of a UNIX system. What are the layers? What does it mean to say they are layers?

A UNIX system has essentially three main layers:

· The hardware

· The operating system kernel

· The user-level programs

The kernel hides the system’s hardware underneath an abstract, high-level programming interface. It is responsible for implementing many of the facilities that users and user-level programs take for granted.

The kernel assembles all of the following UNIX concepts from lower-level hardware features:

· Processes (time-sharing, protected address space)

· Signals and semaphores

· Virtual Memory (swapping, paging, and mapping)

· The filesystem (files, directories, namespace)

· Pipes and network connections (inter-process communication)

JAVA-2

1.why you prefer Java?

Answer: write once ,run anywhere.


2. Name some of the classes which provide the functionality of collation?

Answer: collator, rulebased collator, collationkey, collationelement iterator.


3. Awt stands for? and what is it?

Answer: AWT stands for Abstract window tool kit. It is a is a package that provides an integrated set of classes to manage user interface components.

4. why a java program can not directly communicate with an ODBC driver?

Answer: Since ODBC API is written in C language and makes use of pointers which Java can not support.

5. Are servlets platform independent? If so Why? Also what is the most common application of servlets?

Answer: Yes, Because they are written in Java. The most common application of servlet is to access database and dynamically construct HTTP response

JAVA-3

Question 1: What is the three tier model?
Answer: It is the presentation, logic, backend
Question 2: Why do we have index table in the database?
Answer: Because the index table contain the information of the other tables. It will
be faster if we access the index table to find out what the other contain.
Question 3: Give an example of using JDBC access the database.
Answer:
try
{
Class.forName("register the driver");
Connection con = DriverManager.getConnection("url of db", "username","password");
Statement state = con.createStatement();
state.executeUpdate("create table testing(firstname varchar(20), lastname varchar(20))");
state.executeQuery("insert into testing values('phu','huynh')");
state.close();
con.close();
}
catch(Exception e)
{
System.out.println(e);
}
Question 4: What is the different of an Applet and a Java Application
Answer: The applet doesn't have the main function
Question 5: How do we pass a reference parameter to a function in Java?
Answer: Even though Java doesn't accept reference parameter, but we can
pass in the object for the parameter of the function.
For example in C++, we can do this:

void changeValue(int& a)
{
a++;
}
void main()
{
int b=2;
changeValue(b);
}

however in Java, we cannot do the same thing. So we can pass the
the int value into Integer object, and we pass this object into the
the function. And this function will change the object.
 

JAVA-4

Q:In Java, what is the difference between an Interface and an Abstract class?

A: An Abstract class declares have at least one instance method that is declared abstract which will be implemented by the subclasses. An abstract class can have instance methods that implement a default behavior. An Interface can only declare constants and instance methods, but cannot implement default behavior.

Q: Can you have virtual functions in Java? Yes or No. If yes, then what are virtual functions?

A: Yes, Java class functions are virtual by default. Virtual functions are functions of subclasses that can be invoked from a reference to their superclass. In other words, the functions of the actual object are called when a function is invoked on the reference to that object.

Q:Write a function to reverse a linked list p ?

A:

Link* reverse_list(Link* p)
{
if (p == NULL)
return NULL;

Link* h = p;
p = p->next;
h->next = NULL;
while (p != null)
{
Link* t = p->next;
p->next = h;
h = p;
p = t;
}

return h;
}
 

Q:In C++, what is the usefulness of Virtual destructors?

A:Virtual destructors are neccessary to reclaim memory that were allocated for objects in the class hierarchy. If a pointer to a base class object is deleted, then the compiler guarantees the various subclass destructors are called in reverse order of the object construction chain.

Q:What are mutex and semaphore? What is the difference between them?

A:A mutex is a synchronization object that allows only one process or thread to access a critical code block. A semaphore on the other hand allows one or more processes or threads to access a critial code block. A semaphore is a multiple mutex.
 

CPP 2

1.Question: Suppose that data is an array of 1000 integers. Write a single function call that will sort the 100 elements data [222] through data [321].
Answer: quicksort ((data + 222), 100);

2.Question: Which recursive sorting technique always makes recursive calls to sort subarrays that are about half size of the original array?
Answer: Mergesort always makes recursive calls to sort subarrays that are about half size of the original array, resulting in O(n log n) time.

3.Question: What is the difference between an external iterator and an internal iterator? Describe an advantage of an external iterator.
Answer: .An internal iterator is implemented with member functions of the class that has items to step through. .An external iterator is implemented as a separate class that can be "attach" to the object that has items to step through. .An external iterator has the advantage that many difference iterators can be active simultaneously on the same object.

4.Question: Why are arrays usually processed with for loop?
Answer: The real power of arrays comes from their facility of using an index variable to traverse the array, accessing each element with the same expression a[i]. All the is needed to make this work is a iterated statement in which the variable i serves as a counter, incrementing from 0 to a.length -1. That is exactly what a loop does.


5.Question: What is an HTML tag?
Answer: An HTML tag is a syntactical construct in the HTML language that abbreviates specific instructions to be executed when the HTML script is loaded into a Web browser. It is like a method in Java, a function in C++, a procedure in Pascal, or a subroutine in FORTRAN.

CPP-3

What is pure virtual function?
A class is made abstract by declaring one or more of its virtual functions to be pure. A pure virtual function is one with an initializer of = 0 in its declaration

Q. Write a Struct Time where integer m, h, s are its members
struct Time
{
int m;
int h;
int s;
};

Q. How do you traverse a Btree in Backward in-order?
Process the node in the right subtree
Process the root
Process the node in the left subtree

Q. What is the two main roles of Operating System?
As a resource manager
As a virtual machine

Q. In the derived class, which data member of the base class are visible?
In the public and protected sections.

CPP-4

Q1 What are the advantages and disadvantages of B-star trees over Binary trees? (Asked by Motorola people)

A1 B-star trees have better data structure and are faster in search than Binary trees, but it's harder to write codes for B-start trees.

Q2 Write the psuedo code for the Depth first Search.(Asked by Microsoft)

A2

dfs(G, v) //OUTLINE
Mark v as "discovered"
For each vertex w such that edge vw is in G:
If w is undiscovered:
dfs(G, w); that is, explore vw, visit w, explore from there
as much as possible, and backtrack from w to v.
Otherwise:
"Check" vw without visiting w.
Mark v as "finished".

Q3 Describe one simple rehashing policy.(Asked by Motorola people)

A3 The simplest rehashing policy is linear probing. Suppose a key K hashes to location i. Suppose other key occupies H[i]. The following function is used to generate alternative locations:

rehash(j) = (j + 1) mod h

where j is the location most recently probed. Initially j = i, the hash code for K. Notice that this version of rehash does not depend on K.

Q4 Describe Stacks and name a couple of places where stacks are useful. (Asked by Microsoft)

A4 A Stack is a linear structure in which insertions and deletions are always made at one end, called the top. This updating policy is called last in, first out (LIFO). It is useful when we need to check some syntex errors, such as missing parentheses.

Q5 Suppose a 3-bit sequence number is used in the selective-reject ARQ, what is the maximum number of frames that could be transmitted at a time? (Asked by Cisco)

A5 If a 3-bit sequence number is used, then it could distinguish 8 different frames. Since the number of frames that could be transmitted at a time is no greater half the numner of frames that could be distinguished by the sequence number, so at most 4 frames can be transmitted at a time.

JAVA-5

1) What is the purpose of garbage collection in Java, and when is it used?

The purpose of garbage collection is to identify and discard objects that are no longer needed by a program so that their resources can be reclaimed and reused. A Java object is subject to garbage collection when it becomes unreachable to the program in which it is used.

2) Describe synchronization in respect to multithreading.

With respect to multithreading, synchronization is the capability to control the access of multiple threads to shared resources. Without synchonization, it is possible for one thread to modify a shared variable while another thread is in the process of using or updating same shared variable. This usually leads to significant errors.

3) How is JavaBeans differ from Enterprise JavaBeans?

The JavaBeans architecture is meant to provide a format for general-purpose components. On the other hand, the Enterprise JavaBeans architecture provides a format for highly specialized business logic components.

4) In what ways do design patterns help build better software?

Design patterns helps software developers to reuse successful designs and architectures. It helps them to choose design alternatives that make a system reusuable and avoid alternatives that compromise reusability through proven techniques as design patterns.

5) Describe 3-Tier Architecture in enterprise application development.

In 3-tier architecture, an application is broken up into 3 separate logical layers, each with a well-defined set of interfaces. The presentation layer typically consists of a graphical user interfaces. The business layer consists of the application or business logic, and the data layer contains the data that is needed for the application.

CPP-5

1. In C++, what is the difference between method overloading and method overwriting?

Overloading a method (or function) in C++ is the ability for functions of the same name to be defined as long as these methods have different signatures (different set of parameters). Method overwriting is the ability of the inherited class rewriting the virtual method of the base class.

2. What methods can be overwritten in Java?

In C++ terminalogy, all public methods in Java are virtual. Therefore, all Java methods can be overwritten in subclasses except those that are declared final, static, and private.

3. In C, What is the difference between a static variable and global variable?

A static variable declared outside of any function is accessible only to all the functions defined in the same file (as the static variable). However, a global variable can be accessed by any function (including the ones from different files).

4. In C, why is the void pointer useful?

The void pointer is useful becuase it is a generic pointer that any pointer can be cast into and back again without loss of information.

5. What are the defining traits of an object-oriented language?

The defining traits of an object-oriented langauge are:

CPP-6

Q: What is the difference between Stack and Queue?

A: Stack is a Last In First Out (LIFO) data structure.

Queue is a First In First Out (FIFO) data structure

Q: Write a fucntion that will reverse a string. (Microsoft)

A: char *strrev(char *s)

{

int i = 0, len = strlen(s);

char *str;

if ((str = (char *)malloc(len+1)) == NULL) /*cannot allocate memory */

err_num = 2;

return (str);

}

while(len)

str[i++]=s[--len];

str[i] = NULL;

return (str);

}

Q: What is the software Life-Cycle?

A: The software Life-Cycle are

1) Analysis and specification of the task

2) Design of the algorithms and data structures

3) Implementation (coding)

4) Testing

5) Maintenance and evolution of the system

6) Obsolescence

Q: What is the difference between a Java application and a Java applet?

A: The difference between a Java application and a Java applet is that a

Java application is a program that can be executed using the Java

interpeter, and a JAVA applet can be transfered to different networks

and executed by using a web browser (transferable to the WWW).

Q: Name 7 layers of the OSI Reference Model? (from Cisco)

A: -Application layer

-Presentation layer

-Session layer

-Transport layer

-Network layer

-Data Link layer

-Physical layer

CPP-7

1. How do you write a function that can reverse a linked-list? (Cisco System)

void reverselist(void)

{

if(head==0)

return;

if(head->next==0)

return;

if(head->next==tail)

{

head->next = 0;

tail->next = head;

}

else

{

node* pre = head;

node* cur = head->next;

node* curnext = cur->next;

head->next = 0;

cur->next = head;

for(; curnext!=0; )

{

cur->next = pre;

pre = cur;

cur = curnext;

curnext = curnext->next;

}

curnext->next = cur;

}

}

2. What is polymorphism?

Polymorphism is the idea that a base class can be inherited by several classes. A base class pointer can point to its child class and a base class array can store different child class objects.

3. How do you find out if a linked-list has an end? (i.e. the list is not a cycle)

You can find out by using 2 pointers. One of them goes 2 nodes each time. The second one goes at 1 nodes each time. If there is a cycle, the one that goes 2 nodes each time will eventually meet the one that goes slower. If that is the case, then you will know the linked-list is a cycle.

4. How can you tell what shell you are running on UNIX system?

You can do the Echo $RANDOM. It will return a undefined variable if you are from the C-Shell, just a return prompt if you are from the Bourne shell, and a 5 digit random numbers if you are from the Korn shell. You could also do a ps -l and look for the shell with the highest PID.

5. What is Boyce Codd Normal form?

A relation schema R is in BCNF with respect to a set F of functional dependencies if for all functional dependencies in F+ of the form a->b, where a and b is a subset of R, at least one of the following holds:

a->b is a trivial functional dependency (b is a subset of a)

a is a superkey for schema R

Java Server Pages-JSP

Q: What are the most common techniques for reusing functionality in object-oriented systems?
A: The two most common techniques for reusing functionality in object-oriented systems are class inheritance and object composition.

Class inheritance lets you define the implementation of one class in terms of another's. Reuse by subclassing is often referred to as white-box reuse.
Object composition is an alternative to class inheritance. Here, new functionality is obtained by assembling or composing objects to get more complex functionality. This is known as black-box reuse.

Q: Why would you want to have more than one catch block associated with a single try block in Java?
A: Since there are many things can go wrong to a single executed statement, we should have more than one catch(s) to catch any errors that might occur.

Q: What language is used by a relational model to describe the structure of a database?
A: The Data Definition Language.

Q: What is JSP? Describe its concept.
A: JSP is the JavaServer Page. The JavaServer Page concept is to provide an HTML document with the ability to plug in content at selected locations in the document. (This content is then supplied by the Web server along with the rest of the HTML document at the time the document is downloaded).

Q: What does the JSP engine do when presented with a JavaServer Page to process?
A: The JSP engine builds a servlet. The HTML portions of the JavaServer Page become Strings transmitted to print methods of a PrintWriter object. The JSP tag portions result in calls to methods of the appropriate JavaBean class whose output is translated into more calls to a println method to place the result in the HTML document

CPP-8

From Microsoft) Assume I have a linked list contains all of the alphabets from ‘A’ to ‘Z’. I want to find the letter ‘Q’ in the list, how does you perform the search to find the ‘Q’?
Answer: In a linked list, we only know about the header and other elements are invisible unless we go through the node one by one. Since we have go through every single node to find ‘Q’, the search time for a linked list is linear which is O (N).

(From IBM) How do you think about your school?
Answer: I enjoy studying in our school because we have many professors and instructors are from local companies. Their professions lead us more close to local industries.

(From IBM) What classes you have enjoyed the most during your school years?
Answer: I like the class I am taking this semester, which involves a group project that needs great amount of team efforts. I really enjoy work with a group of people because we can learn new materials mutually.

(From IBM) According to your group project you just mentioned, what’s the responsibility for each member in your group?
Answer: We have five people in our group. So far we have two web servers set up; one will be the back up system and the other will be the main system. Our leader coordinates the schedule. Two members are working on the database and do the coding for the connection between database and Java serverlets. One member is working on the user browser interface. All members will assign some classes to work on and perform the final test at the end. We have group meeting every Saturday to ensure our schedule is on track.

Can you work under pressure?
Answer: I worked for Sega of America in the hardware development group three years ago. They were working on the next generation of gaming machine (which is the “Dreamcast” we seen today in the market). My duty was to ensure the quality of prototypes that just built from manufacture were ready for engineers to test. I managed to balance the schedules and pressures from school and work.

Networking-2

Question 1: How does the race condition occur?

It occurs when two or more processes are reading or writing some shared data and

the final result depends on who runs precisely when.

Question 2: What is multiprogramming?

Multiprogramming is a rapid switching of the CPU back and forth between processes.

Question 3: Name the seven layers of the OSI Model and describe them briefly.

Physical Layer - covers the physical interface between devices and the rules by which bits are passed from one to another.

Data Link Layer - attempts o make the physical link reliable and provides the means to

activate, maintain, and deactivate the link.

Network Layer - provides for the transfer of information between end systems across

some sort communications network.

Transport Layer - provides a mechanism for the exchange of data between end system.

Session Layer - provides the mechanism for controlling the dialogue between applications

in end systems.

Presentation Layer - defines the format of the data to be exchanged between applications

and offers application programs a set of data transformation services.

Application Layer - provides a means for application programs to access the OSI environment.

Question 4: What is the difference between TCP and UDP?

TCP and UDP are both transport-level protocols. TCP is designed to provide reliable

communication across a variety of reliable and unreliable networks and internets.

UDP provides a connectionless service for application-level procedures. Thus, UDP is basically

an unreliable service; delivery and duplicate protection are not guareented.

Question 5: What does a socket consists of?

The combination of an IP address and a port number is called a socket.

UNIX-2

Question 1: What is the major advantage of a hash table? (Asked by Silicon Magic Corp. people)

Answer: The major advantage of a hash table is its speed. Because the hash function is to take a range of key values and transform them into index values in such a way that the key values are distributed randomly across all the indices of a hash table.

Question 2: What are the techniques that you use to handle the collisions in hash tables?(Asked by Silicon Magic Corp. people)

Answer: We can use two major techniques to handle the collisions. They are open addressing and separate chaining. In open addressing, data items that hash to a full array cell are placed in another cell in the array. In separate chaining, each array element consist of a linked list. All data items hashing to a given array index are inserted in that list.

Question 3: In Unix OS, what is the file server? (Asked by Silicon Magic Corp. people)

Answer: The file server is a machine that shares its disk storage and files with other machines on the network.

Question 4: What is NFS? What is its job?(Asked by Silicon Magic Corp. people)

Answer: NFS stands for Network File System. NFS enables filesystems physically residing on one computer system to be used by other computers in the network, appearing to users on the remote host as just another local disk.

Question 5: What is CVS? List some useful CVS commands.(Asked by Silicon Magic Corp.people)

Anser: CVS is Concurrent Version System. It is the front end to the RCS revision control system which extends the notion of revision control from a collection of files in a single directory to a hierarchical collection of directories consisting of revision controlled files. These directories and files can be combined together to form a software release.
There are some useful commands that are being used very often. They are

cvs checkout
cvs update
cvs add
cvs remove
cvs commit
 

Networking-3

Q1. Name of seven layers in Open System Interconnection model.

A. They are Application, Presentation, Session, Transport, Network, Data link, and Physical.

Q2. What is the time complexity of matrix multiplication ?

void Mult_Matrix(matrix A, matrix B, matrix C)
{
int i, j, k;
for ( i = 1; i < N; i++)
for ( j = 1; j < N; j++ )
{
C[i][j] = 0;
for ( k = 0; k < N; k++ )
C[i][j] = A[i][j]*B[k][j];
}
retrun;
}

A. The time comlexity of matrix mulitiplication is O(N^3)

Q3. What is the null pointer in C++ ?

A. The null pointer is a special C++ pointer value that can be used for any pointer that doesn't pointer anywhere. It can be written as the constant NULL form stlib.h

Q4. What is the goal of the shortest distance algorithm ?

A. The goal is to completely fill the distance array so that for each vertex v, the value of distance[v] is the weight of the shortest path from start to v.

Q5. What is the difference between an abstract class and an interface?

A.

An abstract class may have fields and some implemented methods.

An interface has no implementation; only constants and method declarations.

Networking-4

Q: What are the seven layers of the OSI model?

A: The layers are physical, data link, network, transport, session, presentation, and application layers.

Q: In the TCP client-servel model, how does the three-way handshake work in opening connection?

A: The client first sends a packet with sequence "x" to the server. When the server receives this packet, the server will send back another packet with sequence "y", acknowledging the request of the client. When the client receives the acknowledgement from the server, the client will then send an acknowledge back to the server for acknowledging that sequence "y" has been received.

Q: What is the purpose of exchanging beginning sequence numbers during the the connection in the TCP client-server model?

A: To ensure that any data lost during data transfer can be retransmitted.

Q: How does Asynchronous Transfer Mode (ATM) work?

A: ATM works by transmitting all traffic in small, fixed-sized cells. These small, fixed-size cells reduces queuing delay and can be switched quickly. ATM fits into layer 2 of the OSI model and provides functions for framing and error correction. At the port interface, ATM switches convert cells into frames, and vice versa. ATM provides Quality of Service and traffic shaping.

Q: Given a Class B Network with subnet mask of 255.255.248.0 and a packet addressed to 130.40.32.16, what is the subnet address?

A: Take the 2 addresses, write them in binary form, then AND them. The answer is 130.40.32.0

WEB Development-JAVA

What is a Servlet?

Answer: Servlets are modules of Java code that run in a server

application (hence the name "Servlets", similar to "Applets"

on the client side) to answer client requests.

What advantages does CMOS have over TTL(transitor transitor logic)? (ALCATEL)

low power dissipation

pulls up to rail

easy to interface

How is Java unlike C++? (Asked by Sun)

Two classes of language features have been removed from C++ to make it Java. These are those language features which make C++ unsafe and those which make it hard to read.

What is HTML (Hypertext Markup Language)?

HTML (HyperText Markup Language) is the set of "markup" symbols or tags inserted in a file intended for display on a World Wide Web browser. The markup tells the Web browser how to display a Web page's words and images for the user.

what is class?

Answer: A class describes a collection of related objects.

CPP-9, Networking

Q: Write a short code using C++ to print out all odd number from 1 to 100 using a for loop(Asked by Intacct.com people)
A.for(int i = 1; i<100;i++)
{
int number = i %2;
if(number!=0)
cout<<"The odd number are"<<number<<endl;
}

2.Q: Name sevent ISO layers and what layer is the IP operated from?( Asked by Cisco system people)

A.Application, Presentation, Session, Transport, Network, Data link and Physical. The IP is operated in the Network layer.

3.Q: Write a program that ask for user input from 5 to 9 then calculate the average( Asked by Cisco system people)

A.int main()
{
int MAX=4;
int total =0;
int average=0;
int numb;
cout<<"Please enter your input from 5 to 9";
cin>>numb;
if((numb <5)&&(numb>9))
cout<<"please re type your input";
else
for(i=0;i<=MAX; i++)
{
total = total + numb;
average= total /MAX;
}
cout<<"The average number is"<<average<<endl;

return 0;
}

4.Q: Can you be bale to identify between Straight- through and Cross- over cable wiring? and in what case do you use Straight- through and Cross-over? (Asked by Cisco system people)

A. Straight-through is type of wiring that is one to to one connection Cross- over is type of wiring which those wires are got switched

We use Straight-through cable when we connect between NIC Adapter and Hub. Using Cross-over cable when connect between two NIC Adapters or sometime between two hubs.

5.Q: If you hear the CPU fan is running and the monitor power is still on, but you did not see any thing show up in the monitor screen. What would you do to find out what is going wrong? (Asked by WNI people)

A. I would use the ping command to check whether the machine is still alive(connect to the network) or it is dead.

JAVA-6, CPP

QUESTION: What is a JavaBean? (asked by Lifescan inc)

ANSWER: JavaBeans are reusable software components written in the Java programming language, designed to be manipulated visually by a software develpoment environment, like JBuilder or VisualAge for Java. They are similar to Microsoft's ActiveX components, but designed to be platform-neutral, running anywhere there is a Java Virtual Machine (JVM).

QUESTION: What are the seven layers(OSI model) of networking? (asked by Caspio.com)

ANSWER: 1.Physical, 2.Data Link, 3.Network, 4.Transport, 5.Session, 6.Presentation and 7.Application Layers.

QUESTION: What are some advantages and disadvantages of Java Sockets? (asked by Arashsoft.com)

ANSWER:
Advantages of Java Sockets:

Sockets are flexible and sufficient. Efficient socket based programming can be easily implemented for general communications.

Sockets cause low network traffic. Unlike HTML forms and CGI scripts that generate and transfer whole web pages for each new request, Java applets can send only necessary updated information.

Disadvantages of Java Sockets:

Security restrictions are sometimes overbearing because a Java applet running in a Web browser is only able to establish connections to the machine where it came from, and to nowhere else on the network

Despite all of the useful and helpful Java features, Socket based communications allows only to send packets of raw data between applications. Both the client-side and server-side have to provide mechanisms to make the data useful in any way.

Since the data formats and protocols remain application specific, the re-use of socket based implementations is limited.

QUESTION: What is the difference between a NULL pointer and a void pointer? (asked by Lifescan inc)

ANSWER: A NULL pointer is a pointer of any type whose value is zero. A void pointer is a pointer to an object of an unknown type, and is guaranteed to have enough bits to hold a pointer to any object. A void pointer is not guaranteed to have enough bits to point to a function (though in general practice it does).

QUESTION: What is encapsulation technique? (asked by Microsoft)

ANSWER: Hiding data within the class and making it available only through the methods. This technique is used to protect your class against accidental changes to fields, which might leave the class in an inconsistent state.

CPP-10

What is a Make file?(Fujitsu)
Ans: Make file is a utility in Unix to help compile large programs. It helps by only compiling the portion of the program that has been changed.

2. What is deadlock?(Novell)
Deadlock is a situation when two or more processes prevent each other from running. Example: if T1 is holding x and waiting for y to be free and T2 holding y and waiting for x to be free deadlock happens.

3. What is a Semaphore?(Novell)
Semaphore is a special variable, it has two methods: up and down. Semaphore performs atomic operations, which means ones a semaphore is called it can not be inturrupted.

4. Is C an Object Oriented language?(Microsoft)
C is not an Object Oriented language, but limited Object Oriented programming can be done in C.

5. What is difference between C++ and Java?
C++ has pointers Java does not.

Java is platform independent C++ is not.

Java has garbage collection C++ does not.